package billing

import (
	"encoding/json"
	"fmt"
	"net"
	"strings"
)

// ========================================
// 付费页面生成器 (Payment Page Generator)
// 根据请求类型生成HTML收银台页面或JSON响应
// ========================================

// PaymentPageGenerator 付费页面生成器
type PaymentPageGenerator struct {
	brandName    string // 品牌名称
	supportEmail string // 支持邮箱
}

// NewPaymentPageGenerator 创建付费页面生成器
func NewPaymentPageGenerator(brandName, supportEmail string) *PaymentPageGenerator {
	if brandName == "" {
		brandName = "Internal Net Bridge"
	}
	if supportEmail == "" {
		supportEmail = "support@internalnetbridge.com"
	}

	return &PaymentPageGenerator{
		brandName:    brandName,
		supportEmail: supportEmail,
	}
}

// GenerateResponse 生成响应
// 根据请求类型自动选择HTML或JSON格式
func (g *PaymentPageGenerator) GenerateResponse(result *InterceptResult, ctx *InterceptContext) []byte {
	// 🚀 智能判断：优先根据HTTP头判断，其次根据协议
	if ctx.Protocol == "HTTP" {
		// HTTP协议：根据Accept头或IsJSONRequest判断
		if ctx.IsJSONRequest || strings.Contains(strings.ToLower(ctx.HTTPHeaders["accept"]), "application/json") {
			return g.GenerateJSON(result, ctx)
		}
		// 默认返回HTML
		return g.GenerateHTML(result, ctx)
	}

	// TCP/QUIC协议：返回JSON（客户端需要解析）
	return g.GenerateJSON(result, ctx)
}

// GenerateHTML 生成HTML收银台页面
func (g *PaymentPageGenerator) GenerateHTML(result *InterceptResult, ctx *InterceptContext) []byte {
	// 根据付费类型选择展示方式
	var paymentContent string

	if result.PaymentType == PaymentTypeQRCode {
		// 二维码展示
		paymentContent = fmt.Sprintf(`
			<div class="qrcode-container">
				<img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=%s" 
					 alt="扫码支付" class="qrcode">
				<p class="qrcode-tip">请使用手机扫描二维码完成支付</p>
			</div>
			<a href="%s" class="payment-link" target="_blank">或点击这里使用浏览器支付</a>
		`, result.PaymentURL, result.PaymentURL)
	} else {
		// 收银台链接
		paymentContent = fmt.Sprintf(`
			<a href="%s" class="payment-button" target="_blank">
				前往收银台支付
			</a>
			<p class="payment-tip">点击按钮将跳转到安全的支付页面</p>
		`, result.PaymentURL)
	}

	// 构建完整HTML页面
	html := fmt.Sprintf(`<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>服务暂停 - %s</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%%, #764ba2 100%%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            max-width: 600px;
            width: 100%%;
            padding: 50px 40px;
            text-align: center;
        }
        .icon {
            font-size: 80px;
            margin-bottom: 20px;
        }
        h1 {
            color: #333;
            font-size: 32px;
            margin-bottom: 10px;
        }
        .reason {
            color: #666;
            font-size: 18px;
            margin-bottom: 30px;
            line-height: 1.6;
        }
        .info-box {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
            text-align: left;
        }
        .info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 12px;
            font-size: 14px;
        }
        .info-row:last-child {
            margin-bottom: 0;
        }
        .info-label {
            color: #888;
            font-weight: 500;
        }
        .info-value {
            color: #333;
            font-weight: 600;
        }
        .payment-button {
            display: inline-block;
            background: linear-gradient(135deg, #667eea 0%%, #764ba2 100%%);
            color: white;
            padding: 16px 48px;
            border-radius: 50px;
            text-decoration: none;
            font-size: 18px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
        }
        .payment-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
        }
        .payment-link {
            display: block;
            color: #667eea;
            text-decoration: none;
            margin-top: 15px;
            font-size: 14px;
        }
        .payment-link:hover {
            text-decoration: underline;
        }
        .payment-tip {
            color: #999;
            font-size: 14px;
            margin-top: 15px;
        }
        .qrcode-container {
            margin: 30px 0;
        }
        .qrcode {
            border: 3px solid #667eea;
            border-radius: 10px;
            padding: 10px;
            background: white;
        }
        .qrcode-tip {
            color: #666;
            margin-top: 15px;
            font-size: 14px;
        }
        .footer {
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #e0e0e0;
            color: #999;
            font-size: 13px;
        }
        .footer a {
            color: #667eea;
            text-decoration: none;
        }
        .footer a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="icon">💳</div>
        <h1>服务暂停</h1>
        <p class="reason">%s</p>
        
        <div class="info-box">
            <div class="info-row">
                <span class="info-label">订单号</span>
                <span class="info-value">%s</span>
            </div>
            <div class="info-row">
                <span class="info-label">隧道ID</span>
                <span class="info-value">%s</span>
            </div>
            <div class="info-row">
                <span class="info-label">用户ID</span>
                <span class="info-value">%s</span>
            </div>
        </div>

        %s

        <div class="footer">
            如有疑问，请联系 <a href="mailto:%s">%s</a><br>
            <span style="color: #ccc;">Powered by %s</span>
        </div>
    </div>
</body>
</html>`,
		g.brandName,
		result.Reason,
		result.OrderID,
		shortenID(ctx.TunnelID),
		shortenID(ctx.UserID),
		paymentContent,
		g.supportEmail,
		g.supportEmail,
		g.brandName,
	)

	return []byte(html)
}

// GenerateJSON 生成JSON响应
func (g *PaymentPageGenerator) GenerateJSON(result *InterceptResult, ctx *InterceptContext) []byte {
	response := map[string]interface{}{
		"success": false,
		"error": map[string]interface{}{
			"code":    "SERVICE_SUSPENDED",
			"message": result.Reason,
			"payment": map[string]interface{}{
				"type":      result.PaymentType,
				"url":       result.PaymentURL,
				"order_id":  result.OrderID,
				"tunnel_id": ctx.TunnelID,
				"user_id":   ctx.UserID,
			},
		},
	}

	// 添加额外信息
	if result.Extra != nil {
		response["error"].(map[string]interface{})["details"] = result.Extra
	}

	jsonBytes, _ := json.MarshalIndent(response, "", "  ")
	return jsonBytes
}

// SendToClient 发送响应到客户端
// 根据协议类型选择不同的发送方式
func (g *PaymentPageGenerator) SendToClient(conn net.Conn, result *InterceptResult, ctx *InterceptContext) error {
	responseBody := g.GenerateResponse(result, ctx)

	if ctx.Protocol == "HTTP" {
		// HTTP协议：构建完整的HTTP响应
		var contentType string
		if ctx.IsJSONRequest || strings.Contains(strings.ToLower(ctx.HTTPHeaders["accept"]), "application/json") {
			contentType = "application/json; charset=utf-8"
		} else {
			contentType = "text/html; charset=utf-8"
		}

		httpResponse := fmt.Sprintf(
			"HTTP/1.1 402 Payment Required\r\n"+
				"Content-Type: %s\r\n"+
				"Content-Length: %d\r\n"+
				"Connection: close\r\n"+
				"X-Payment-Required: true\r\n"+
				"X-Order-ID: %s\r\n"+
				"\r\n"+
				"%s",
			contentType,
			len(responseBody),
			result.OrderID,
			string(responseBody),
		)

		_, err := conn.Write([]byte(httpResponse))
		return err
	}

	// TCP/QUIC协议：直接发送JSON（客户端需要处理）
	_, err := conn.Write(responseBody)
	return err
}

// shortenID 缩短ID显示（显示前8位+...）
func shortenID(id string) string {
	if len(id) > 12 {
		return id[:8] + "..."
	}
	return id
}
